﻿///***************************************************************
/// 시  스  템 : Updms.Mny
/// 단위시스템 : MNY
/// 계      층 : Presentation Layer
/// 프로그램명 : Mny2013r
/// 파  일  명 : Mny2013r.aspx.cs
/// 설      명 : 예산시뮬레이션
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2008-08-11 송시명   최초 작성
///***************************************************************
using System;
using System.Data;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

using SMFramework.Data;
using SMFramework.Utility;

using Base.AppFramework.Web.UI.CommandBar;
using Base.Dac;
using Updms.Mny.Exe;


namespace Updms.Mny
{
	public partial class Mny2013r : Updms.Common.BaseClass.PageBase
	{
		#region 전역영역

		//프로그램상수
		public static readonly string PID = "Mny2013r";
		public static readonly string gs_path_info = "/updms/Mny/" + PID + ".aspx";

		Global global = new Global();
		CommCode.Mny mny = new CommCode.Mny(LANG_SET);

		//검색
		protected string kw1 = "";	// 기준년월

		//메뉴 선택값
		protected string gs_sm = "";

		//페이지모드
		private string gs_page_mode = "";	// 팝업으로 열지 여부

		#endregion

		#region Page_Load, OnPageLoad

		protected void Page_Load(object sender, EventArgs e)
		{
			SetInit();
			if (!Page.IsPostBack)
			{
				// 최초 화면 로딩시 처리해야 할 부분
				OnPageLoad();
				initMsgBoxNoAjax();
			}
		}

		// OnPageLoad
		private void OnPageLoad()
		{
			SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
			SetClientScript();
			SetYearMonth();
			SetSearchTarget();
			SetSearchParameter();
			SearchProcess();
		}

		#endregion

		#region InitializeComponent

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);
		}

		#endregion

		#region SetClientScript

		private void SetClientScript()
		{
			//onkeyup 이벤트추가(수입)
			for (int i = 1; i <= 20; i++)
			{
				TextBox tb_in = new TextBox();

				tb_in = (TextBox)table_in_amount.FindControl("txt_amount_in_" + i.ToString());
				tb_in.Attributes.Add("onkeyup", "form1.txt_amount_in_"+ i.ToString()+".value=addComma(form1.txt_amount_in_"+ i.ToString()+".value);calcInSum();");
			}

			//onkeyup 이벤트추가(지출 -> 금액(입력), 금액(원금))
			for (int i = 1; i <= 45; i++)
			{
				TextBox tb_out_input = new TextBox();
				TextBox tb_out_org = new TextBox();

				tb_out_input = (TextBox)table_out_amount.FindControl("txt_amount_out_input_" + i.ToString());
				tb_out_input.Attributes.Add("onkeyup", "form1.txt_amount_out_input_" + i.ToString() + ".value=addComma(form1.txt_amount_out_input_" + i.ToString() + ".value);calcOutInputSum('" + i.ToString() + "');calcOutSum();");

				tb_out_org = (TextBox)table_out_amount.FindControl("txt_amount_out_org_" + i.ToString());
				tb_out_org.Attributes.Add("onkeyup", "form1.txt_amount_out_org_" + i.ToString() + ".value=addComma(form1.txt_amount_out_org_" + i.ToString() + ".value);calcOutInputSum('" + i.ToString() + "');calcOutSum();");
			}

			//onkeyup 이벤트추가(지출,저축)
			for (int i = 1; i <= 45; i++)
			{
				TextBox tb_out = new TextBox();

				tb_out = (TextBox)table_out_amount.FindControl("txt_amount_out_" + i.ToString());
				tb_out.Attributes.Add("onkeyup", "form1.txt_amount_out_" + i.ToString() + ".value=addComma(form1.txt_amount_out_" + i.ToString() + ".value);calcOutSum();");
			}

			// 결과금액
			txt_amount_balance.Attributes.Add("onkeyup", "form1.txt_amount_balance.value=addComma(form1.txt_amount_balance.value);calcResultAmount();");
		}

		#endregion

		#region SetInit, SetSearchParameter

		//초기값설정
		private void SetInit()
		{
			lbl_search_flag.Text = "INIT";
			
			gs_sm = (Request.QueryString["sm"] == null || Request.QueryString["sm"].Trim().Length != 7)
					? global.GetDirDepth(PID) : Request.QueryString["sm"].ToString();

			gs_page_mode = (Request.QueryString["page_mode"] == null || Request.QueryString["page_mode"].Trim().Length == 0)
					? "" : Request.QueryString["page_mode"].ToString();
		}

		//검색파라미터
		private void SetSearchParameter()
		{
			switch (lbl_search_flag.Text.Trim().ToUpper())
			{
				case "INIT":
					if (String.IsNullOrEmpty(Request.QueryString["kw1"]))	// url에 값이 없으면
					{
						kw1 = ddl_search_base_dt_year.SelectedValue + "-" + ddl_search_base_dt_month.SelectedValue;
					}
					else
					{
						kw1 = Server.UrlDecode(Request.QueryString["kw1"]);
						ddl_search_base_dt_year.SelectedValue = kw1.Substring(0, 4).ToString();
						ddl_search_base_dt_month.SelectedValue = kw1.Substring(5, 2).ToString();
					}
					break;
				case "SEARCH":
					kw1 = ddl_search_base_dt_year.SelectedValue + "-" + ddl_search_base_dt_month.SelectedValue;
					break;
			}
		}		

		#endregion

		#region 마스터 Method (SetYearMonth, SetSearchTarget)

		//년월
		private void SetYearMonth()
		{
			ddl_search_base_dt_year.Items.Clear();

			int li_f_year = Convert.ToInt32(SEARCH_Y_MIN);
			int li_t_year = Convert.ToInt32(DateUtil.GetYearEx(1, "yyyy"));
			for (int i = li_f_year; i <= li_t_year; i++)
			{
				string ls_year = i.ToString();
				ddl_search_base_dt_year.Items.Add(new ListItem(ls_year, ls_year));
			}

			ddl_search_base_dt_year.SelectedValue = DateUtil.GetYearEx(0, "yyyy"); // 현재년도
			ddl_search_base_dt_month.SelectedValue = DateUtil.GetMonthEx(0, "MM"); // 현재월
		}

		//조회대상
		private void SetSearchTarget()
		{
			mny.SetSearchTarget(rbl_search_target);
		}

		#endregion

		#region 마스터 Method (SetPrevNextMonth, SetEnabledMonthBtn, SetThisMonth)

		//이전달, 다음달버튼 누르면
		private void SetPrevNextMonth(int pi_month_cnt)
		{
			string ls_ym = ddl_search_base_dt_year.SelectedValue + "-" + ddl_search_base_dt_month.SelectedValue;
			string ls_calc_ym = DateUtil.GetCalcMonth(ls_ym, pi_month_cnt, "yyyy-MM");

			if (WebControlUtil.CheckDdlValue(ddl_search_base_dt_year, ls_calc_ym.Substring(0, 4).ToString()))
			{
				ddl_search_base_dt_year.SelectedValue = ls_calc_ym.Substring(0, 4).ToString();
				ddl_search_base_dt_month.SelectedValue = ls_calc_ym.Substring(5, 2).ToString();
			}

			//버튼처리
			SetEnabledMonthBtn();
		}

		//이전달, 다음달버튼 처리
		private void SetEnabledMonthBtn()
		{
			ibtn_prev_month.Enabled
				= (ddl_search_base_dt_year.SelectedIndex == 0 && ddl_search_base_dt_month.SelectedIndex == 0) ? false : true;

			ibtn_next_month.Enabled
				= (ddl_search_base_dt_year.SelectedIndex == ddl_search_base_dt_year.Items.Count - 1 && ddl_search_base_dt_month.SelectedIndex == 11) ? false : true;
		}

		//당월설정
		private void SetThisMonth()
		{
			string ls_this_ym = DateUtil.GetNow("yyyy-MM");
			ddl_search_base_dt_year.SelectedValue = ls_this_ym.Substring(0, 4).ToString();
			ddl_search_base_dt_month.SelectedValue = ls_this_ym.Substring(5, 2).ToString();
			SetEnabledMonthBtn();
		}

		#endregion

		#region 디테일 Method (SetInList, SetOutSaveList, CallAllFunction)

		// 기준년월별 수입(AA001) 내역을 채운다.
		private void SetInList()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_base_dt", typeof(string), kw1);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			using(Mny2013r_NT _Mny2013r_NT = new Mny2013r_NT())
			{
				lo_ds.Merge(_Mny2013r_NT.GetInList(lo_dp));	
			}
			
			int li_count = DataSetUtil.GetRowCount(lo_ds, "UPDMS_MNY_REPORT");

			if (li_count > 0)
			{
				//20개 이상이면 20까지만 보여준다.
				if (li_count > 20)
				{
					li_count = 20;
					CallMsgBoxInAjax("MSG_ERR_120", li_count.ToString());	//수입항목이 20개 이상이므로 금액이 정확하지 않습니다
				}
				
				for (int i = 0; i < li_count; i++)
				{
					string ls_base_dt = DataSetUtil.GetFldStr(lo_ds, "UPDMS_MNY_REPORT", i, "Base_Dt");
					string ls_paymnt_dt = DataSetUtil.GetFldStr(lo_ds, "UPDMS_MNY_REPORT", i, "Paymnt_Dt");
					string ls_class_nm = DataSetUtil.GetFldStr(lo_ds, "UPDMS_MNY_REPORT", i, "Class_Nm");
					string ls_account = DataSetUtil.GetFldStr(lo_ds, "UPDMS_MNY_REPORT", i, "Account_Nm");
					string ls_amount = DataSetUtil.GetFldStr(lo_ds, "UPDMS_MNY_REPORT", i, "Amount");

					int j = i + 1;
					
					((Label)table_in_amount.FindControl("lbl_base_dt_in_" + j.ToString())).Text = ls_base_dt;
					((Label)table_in_amount.FindControl("lbl_paymnt_dt_in_" + j.ToString())).Text = ls_paymnt_dt;
					((Label)table_in_amount.FindControl("lbl_class_in_" + j.ToString())).Text = ls_class_nm;
					((Label)table_in_amount.FindControl("lbl_account_in_" + j.ToString())).Text = ls_account;
					((TextBox)table_in_amount.FindControl("txt_amount_in_" + j.ToString())).Text = ls_amount;
				}
			}
		}

		// 기준년월별 지출(AA002),저축(AA003) 내역을 채운다.
		private void SetOutSaveList()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_base_dt", typeof(string), kw1);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			using (Mny2013r_NT _Mny2013r_NT = new Mny2013r_NT())
			{
				if (rbl_search_target.SelectedValue == "AG001")
				{
					lo_ds.Merge(_Mny2013r_NT.GetOutSaveListByBudget(lo_dp));	//예산
				}
				else
				{
					lo_ds.Merge(_Mny2013r_NT.GetOutSaveList(lo_dp));
				}
			}

			int li_count = DataSetUtil.GetRowCount(lo_ds, "UPDMS_MNY_REPORT");

			if (li_count > 0)
			{
				mode_flag.Text = rbl_search_target.SelectedValue == "AG002" ? "D" : "I";	//실적에서 가져온거면 삭제후 저장
				
				//45개 이상이면 45까지만 보여준다.
				if (li_count > 45)
				{
					li_count = 45;
					CallMsgBoxInAjax("MSG_ERR_121", li_count.ToString());	//지출항목이 45개 이상이므로 금액이 정확하지 않습니다
				}
				
				for (int i = 0; i < li_count; i++)
				{
					string ls_base_dt	= DataSetUtil.GetFldStr(lo_ds, "UPDMS_MNY_REPORT", i, "Base_Dt");
					string ls_seq		= DataSetUtil.GetFldStr(lo_ds, "UPDMS_MNY_REPORT", i, "Seq");
					string ls_class_nm	= DataSetUtil.GetFldStr(lo_ds, "UPDMS_MNY_REPORT", i, "Class_Nm");
					string ls_account	= DataSetUtil.GetFldStr(lo_ds, "UPDMS_MNY_REPORT", i, "Account");
					string ls_account_nm	= DataSetUtil.GetFldStr(lo_ds, "UPDMS_MNY_REPORT", i, "Account_Nm");
					string ls_amount	= DataSetUtil.GetFldStr(lo_ds, "UPDMS_MNY_REPORT", i, "Amount");

					int j = i + 1;
			
					((Label)table_out_amount.FindControl("lbl_base_dt_out_" + j.ToString())).Text = ls_base_dt;
					((TextBox)table_out_amount.FindControl("txt_seq_out_" + j.ToString())).Text = ls_seq;
					((Label)table_out_amount.FindControl("lbl_class_nm_out_" + j.ToString())).Text = ls_class_nm;
					((TextBox)table_out_amount.FindControl("txt_account_out_" + j.ToString())).Text = ls_account;
					((Label)table_out_amount.FindControl("lbl_account_nm_out_" + j.ToString())).Text = ls_account_nm;
					((TextBox)table_out_amount.FindControl("txt_amount_out_org_" + j.ToString())).Text = ls_amount;
					((TextBox)table_out_amount.FindControl("txt_amount_out_" + j.ToString())).Text = ls_amount;
				}
			}
		}

		// 조회후 자바스크립트 호출
		private void CallAllFunction()
		{
			this.ClientScript.RegisterStartupScript(typeof(Page), "callAllFunction", "callAllFunction();", true);
		}

		#endregion

		#region CRUD (InsertProcess, SearchProcess)

		//반영
		private void InsertProcess()
		{
			using (Mny1013m_RT _Mny1013m_RT = new Mny1013m_RT())
			{
				int li_return = _Mny1013m_RT.InsertProcess(SetValue());
				string ls_msg_id = (li_return > 0) ? "MSG_INF_014" : "MSG_ERR_131";	//반영되었습니다:반영할 항목이 없습니다
				CallMsgBoxNoAjax(ls_msg_id);
			}
		}

		//검색
		private void SearchProcess()
		{
			lbl_search_flag.Text = "SEARCH";
			MSGBOX_SCRIPT = "";
			SetSearchParameter();
			ClearValue();
			SetInList();
			SetOutSaveList();
			CallAllFunction();
		}

		#endregion

		#region SetValue, ClearValue

		//SetValue
		private string SetValue()
		{
			StringBuilder sb = new StringBuilder();
			sb.Append("<UPDMS>");

			string ls_base_ym = ddl_search_base_dt_year.SelectedValue + "-" + ddl_search_base_dt_month.SelectedValue;

			//루프를 돌면서 저장할 데이터를 XML로 만듬
			for (int i = 1; i < 45; i++)
			{
				TextBox tb_seq = new TextBox();
				Label	lb_base_ym = new Label();
				TextBox tb_account = new TextBox();
				TextBox tb_amount = new TextBox();

				tb_seq		= (TextBox)Page.FindControl("txt_seq_out_" + i.ToString());
				lb_base_ym	= (Label)table_out_amount.FindControl("lbl_base_dt_out_" + i.ToString());
				tb_account	= (TextBox)Page.FindControl("txt_account_out_" + i.ToString());
				tb_amount	= (TextBox)table_out_amount.FindControl("txt_amount_out_" + i.ToString());

				if (!String.IsNullOrEmpty(tb_seq.Text))
				{
					sb.Append("<UPDMS_MNY_BUDGET>");
					sb.Append("<Flag>" + mode_flag.Text + "</Flag>");
					sb.Append("<Seq>" + tb_seq.Text + "</Seq>");
					sb.Append("<Base_Ym>" + lb_base_ym.Text + "</Base_Ym>");
					sb.Append("<Account>" + tb_account.Text + "</Account>");
					sb.Append("<Amount>" + ConversionUtil.ExtractNumberStr(ConversionUtil.DefaultValue(tb_amount.Text, "0")) + "</Amount>");
					sb.Append("<Confirm_Yn>Y</Confirm_Yn>");
					sb.Append("<Create_User>" + USER_ID + "</Create_User>");
					sb.Append("<Update_User>" + USER_ID + "</Update_User>");
					sb.Append("</UPDMS_MNY_BUDGET>");
				}
			}
			sb.Append("</UPDMS>");

			//Base.AppFramework.SMEventLog.WriteDataLog("SetValue()", sb.ToString());

			return sb.ToString();
		}	
		
		// ClearValue
		private void ClearValue()
		{
			mode_flag.Text = "";
			
			//수입
			for (int i = 1; i <= 20; i++)
			{
				Label lb_base_dt = new Label();
				Label lb_paymnt_dt = new Label();
				Label lb_class_nm = new Label();
				Label lb_account = new Label();
				TextBox tb_amount = new TextBox();

				lb_base_dt		= (Label)table_in_amount.FindControl("lbl_base_dt_in_" + i.ToString());
				lb_paymnt_dt	= (Label)table_in_amount.FindControl("lbl_paymnt_dt_in_" + i.ToString());
				lb_class_nm		= (Label)table_in_amount.FindControl("lbl_class_in_" + i.ToString());
				lb_account		= (Label)table_in_amount.FindControl("lbl_account_in_" + i.ToString());
				tb_amount		= (TextBox)table_in_amount.FindControl("txt_amount_in_" + i.ToString());

				lb_base_dt.Text = "";
				lb_paymnt_dt.Text = "";
				lb_class_nm.Text = "";
				lb_account.Text = "";
				tb_amount.Text = "";
			}

			//지출,저축
			for (int i = 1; i <= 45; i++)
			{
				Label lb_base_dt = new Label();
				TextBox tb_seq = new TextBox();
				Label lb_class_nm = new Label();
				TextBox tb_account = new TextBox();
				Label lb_account_nm = new Label();
				TextBox tb_amount_input = new TextBox(); //입력
				TextBox tb_amount_org = new TextBox(); //입력
				TextBox tb_amount = new TextBox();

				lb_base_dt	= (Label)table_out_amount.FindControl("lbl_base_dt_out_" + i.ToString());
				tb_seq		= (TextBox)table_out_amount.FindControl("txt_seq_out_" + i.ToString());
				lb_class_nm = (Label)table_out_amount.FindControl("lbl_class_nm_out_" + i.ToString());
				tb_account	= (TextBox)table_out_amount.FindControl("txt_account_out_" + i.ToString());
				lb_account_nm	= (Label)table_out_amount.FindControl("lbl_account_nm_out_" + i.ToString());
				tb_amount_input = (TextBox)table_out_amount.FindControl("txt_amount_out_input_" + i.ToString());
				tb_amount_org = (TextBox)table_out_amount.FindControl("txt_amount_out_org_" + i.ToString());
				tb_amount	= (TextBox)table_out_amount.FindControl("txt_amount_out_" + i.ToString());

				lb_base_dt.Text = "";
				tb_seq.Text = "";
				lb_class_nm.Text = "";
				tb_account.Text = "";
				lb_account_nm.Text = "";
				tb_amount_input.Text = "";
				tb_amount_org.Text = "";
				tb_amount.Text = "";
			}
		}	

		#endregion

		#region Page_PreRender, ChangePageMode

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				using (AccessCheck access = new AccessCheck())
				{
					//접근권한 체크
					if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
					{
						Response.Redirect(URL_NO_AUTHORITY_REDIRECT_BASE);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
					}
					//사용권한별 버튼처리
					PagePreRender.SetVisibleCtrl(this, access.CheckPgmUsingGrant(USER_DIV, PID), access.GetVisibleCtrl(PID));
				}
			}
			ChangePageMode();
		}

		// ChangePageMode
		private void ChangePageMode()
		{
			switch (gs_page_mode)
			{
				case "":		// 처음 페이지로드시
					Top.Visible = true;
					menu_area.Attributes.Add("class", "");
					ibtn_close.Visible = false;
					break;
				case "P":	// 팝업으로 열때
					Top.Visible = false;
					menu_area.Attributes.Add("class", "nodisplay");
					ibtn_close.Visible = true;
					break;
			}
			SetGridViewHeader(global.GetColumnListByPgmId(PID, LANG_SET));
		}

		#endregion			

		#region 버튼이벤트

		//검색
		protected void ibtn_search_Click(object sender, EventArgs e)
		{
			SetEnabledMonthBtn();
			SearchProcess();
		}

		//반영
		protected void ibtn_reflect_Click(object sender, EventArgs e)
		{
			InsertProcess();
		}

		//이전달
		protected void ibtn_prev_month_Click(object sender, EventArgs e)
		{
			SetPrevNextMonth(-1);
			SearchProcess();
		}

		//다음달
		protected void ibtn_next_month_Click(object sender, EventArgs e)
		{
			SetPrevNextMonth(1);
			SearchProcess();
		}

		//당월
		protected void ibtn_this_month_Click(object sender, EventArgs e)
		{
			SetThisMonth();
			SearchProcess();
		}

		#endregion

	}
}
